/**
 * 
 */
package mdb.com.vn.web.beans;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import mdb.com.vn.model.Loans;
import mdb.com.vn.services.MDBServices;
import mdb.com.vn.utils.TextUtil;
import mdb.com.vn.web.view.LoansDataModel;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 * @author tu.dod
 *
 */
@ManagedBean(name = "loansRejectedBean")
@ViewScoped
public class LoansRejectedBean implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private StreamedContent file;
	private boolean btnVisible;
	private boolean btnSaveVisible;
	private List<Loans> listOfLoans;
	private List<Object> listOfobjects;

	private LoansDataModel loansDataModel;
	private Loans loansSelected;

	@ManagedProperty("#{mdbServices}")
	private MDBServices mdbServices;
	
	@PostConstruct
	public void init(){
		listOfLoans = new ArrayList<Loans>();
		listOfLoans = mdbServices.getLoansByStatus(TextUtil.REJECTED);
		loansDataModel = new LoansDataModel(listOfLoans);
	}

	public void createExcelLoansByPoi() {
//		Row row = null;
//		Cell cell = null;
//		try {
//			Workbook wb = new HSSFWorkbook();
//			HSSFCellStyle styleHeader = (HSSFCellStyle) wb.createCellStyle();
//			HSSFFont fontHeader = (HSSFFont) wb.createFont();
//			fontHeader.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//			styleHeader.setFont(fontHeader);
//			Sheet sheet = wb.createSheet("TIEN VAY KHONG HOP LE");
//			row = sheet.createRow((short) 0);
//			List<String> columnNames = new ArrayList<String>();
//
//			columnNames.add("Điểm giao dịch");
//			columnNames.add("Ngày tạo");
//			columnNames.add("Tên khách hàng");
//			columnNames.add("Số CIF");
//			columnNames.add("Số điện thoại");
//			columnNames.add("Số hợp đồng");
//			columnNames.add("Số tiền giải ngân");
//			columnNames.add("Kỳ hạn (tháng)");
//			columnNames.add("Lãi suất");
//			columnNames.add("Sản phẩm vay");
//			columnNames.add("Dealer");
//			columnNames.add("Nhóm khách hàng");
//			columnNames.add("Tổng số mã dự thưởng");
//			columnNames.add("Mã dự thưởng");
//			for (int i = 0; i < columnNames.size(); i++) {
//				cell = row.createCell(i);
//				cell.setCellValue(columnNames.get(i));
//				cell.setCellStyle(styleHeader);
//			}
//			int j = 1;
//			List<Object[]> tabularData = new ArrayList<Object[]>();
//			for (Loans loans : listOfLoans) {
//				String companyName = mdbServices.getCompanyNameByCode(loans
//						.getBranchCode());
//				if (companyName == null || companyName.equals("")) {
//					companyName = loans.getBranchCode();
//				}
//				Customer customer = mdbServices.getCustomerInfos(
//						loans.getCustomerId());
//				String phone = "";
//				if (customer != null){
//					phone = customer.getPhoneCountryCode()+"-"+customer.getPhoneAreaCode()+"-"+customer.getPhoneNumber();
//				}else{
//					phone = "N/A";
//				}
//				String lkd_num_g1 = mdbServices.getAllLuckyDrawG1Code(loans.getRefNo(), TextUtil.REJECTED);
//				String dealer = loans.getTxnDesc();
//				if(dealer == null|| dealer.equals("")){
//					dealer = "N/A";
//				}
//				tabularData
//						.add(new Object[] {
//								companyName,
//								loans.getCreatedDate(),
//								loans.getCustomerName(),
//								loans.getCustomerId(),
//								phone,
//								loans.getRefNo(),
//								loans.getPrAmount(),
//								loans.getTerm(),
//								loans.getInterestRate(), 
//								loans.getCategory()+loans.getSubProductcode(),
//								dealer,
//								loans.getCustomerType(),
//								loans.getLkdNum(),
//								lkd_num_g1});
//			}
//			
//			HSSFCellStyle styleRow = (HSSFCellStyle) wb
//					.createCellStyle();
//			HSSFFont fontRow = (HSSFFont) wb.createFont();
//			fontRow.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
//			styleRow.setFont(fontRow);
//			
//			for (Object[] temp : tabularData) {
//				row = sheet.createRow((short) j);
//				for (int k = 0; k < temp.length; k++) {
//					cell = row.createCell(k);
//					cell.setCellValue(temp[k].toString());
//					cell.setCellStyle(styleRow);
//				}
//				j++;
//			}
//			String excelFileName = "LOANS_REJECTED_REPORT.xls";
//			FileOutputStream fos = new FileOutputStream(excelFileName);
//			wb.write(fos);
//			fos.flush();
//			fos.close();
//			InputStream stream = new BufferedInputStream(new FileInputStream(
//					excelFileName));
//			file = new DefaultStreamedContent(stream, "application/xls",
//					excelFileName);
//			setBtnVisible(true);
//			FacesContext
//					.getCurrentInstance()
//					.addMessage(
//							null,
//							new FacesMessage(FacesMessage.SEVERITY_INFO,
//									"Xử lý xuất dữ liệu thành công",
//									"Vui lòng nhấn nút 'Tải về máy' để tại file excell về máy."));
//		} catch (Exception e) {
//			setBtnVisible(false);
//			FacesContext.getCurrentInstance().addMessage(
//					null,
//					new FacesMessage(FacesMessage.SEVERITY_ERROR,
//							"Xử lý xuất dữ liệu thất bại",
//							"Vui lòng liên hệ quản trị hệ thống."));
//			e.printStackTrace();
//		}
		
			listOfobjects = mdbServices.getLoansByPropertiesToExcell(TextUtil.REJECTED);
		Row row = null;
		Cell cell = null;
		try {
			Workbook wb = new HSSFWorkbook();
			HSSFCellStyle styleHeader = (HSSFCellStyle) wb.createCellStyle();
			HSSFFont fontHeader = (HSSFFont) wb.createFont();
			fontHeader.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			styleHeader.setFont(fontHeader);
			Sheet sheet = wb.createSheet("HD VAY VI PHAM");
			row = sheet.createRow((short) 0);
			List<String> columnNames = new ArrayList<String>();

			columnNames.add("Điểm giao dịch");
			columnNames.add("Ngày tạo");
			columnNames.add("Tên khách hàng");
			columnNames.add("Số CIF");
			columnNames.add("Số điện thoại");
			columnNames.add("Số hợp đồng");
			columnNames.add("Số tiền giải ngân");
			columnNames.add("Kỳ hạn (tháng)");
			columnNames.add("Lãi suất");
			columnNames.add("Sản phẩm vay");
			columnNames.add("Dealer");
			columnNames.add("Nhóm khách hàng");
			columnNames.add("Tổng số mã dự thưởng");
			columnNames.add("Mã dự thưởng");
			for (int i = 0; i < columnNames.size(); i++) {
				cell = row.createCell(i);
				cell.setCellValue(columnNames.get(i));
				cell.setCellStyle(styleHeader);
			}
			int j = 1;
			HSSFCellStyle styleRow = (HSSFCellStyle) wb.createCellStyle();
			HSSFFont fontRow = (HSSFFont) wb.createFont();
			fontRow.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
			styleRow.setFont(fontRow);

			for (Object object : listOfobjects) {
				Object[] loanObjTemps = (Object[]) object;
				
				Object[] loanObj = new Object[]{
						loanObjTemps[1],
						loanObjTemps[2],
						loanObjTemps[3],
						loanObjTemps[4],
						loanObjTemps[5],
						loanObjTemps[0],
						loanObjTemps[6],
						loanObjTemps[9],
						loanObjTemps[7], 
						loanObjTemps[8],
						loanObjTemps[10],
						loanObjTemps[11],
						loanObjTemps[12],
						loanObjTemps[13]};
				
				row = sheet.createRow((short) j);
				for (int k = 0; k < loanObj.length; k++) {
					cell = row.createCell(k);
					cell.setCellValue(loanObj[k] == null?"N.A":loanObj[k].toString());
					cell.setCellStyle(styleRow);
				}
				loanObj = null;
				j++;

			}
			String excelFileName = "LOANS_REPORT_REJECTED.xls";
			FileOutputStream fos = new FileOutputStream(excelFileName);
			wb.write(fos);
			fos.flush();
			fos.close();
			InputStream stream = new BufferedInputStream(new FileInputStream(
					excelFileName));
			file = new DefaultStreamedContent(stream, "application/xls",
					excelFileName);
			setBtnVisible(true);
			FacesContext
					.getCurrentInstance()
					.addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_INFO,
									"Xử lý xuất dữ liệu thành công",
									"Vui lòng nhấn nút 'Tải về máy' để tại file excell về máy."));
		} catch (Exception e) {
			setBtnVisible(false);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Xử lý xuất dữ liệu thất bại",
							"Vui lòng liên hệ quản trị hệ thống."));
		}
	}

	public void downloadPreventedLoans() {
		file = null;
	}
	/**
	 * @return the btnVisible
	 */
	public boolean isBtnVisible() {
		return btnVisible;
	}

	/**
	 * @param btnVisible the btnVisible to set
	 */
	public void setBtnVisible(boolean btnVisible) {
		this.btnVisible = btnVisible;
	}

	/**
	 * @return the btnSaveVisible
	 */
	public boolean isBtnSaveVisible() {
		return btnSaveVisible;
	}

	/**
	 * @param btnSaveVisible the btnSaveVisible to set
	 */
	public void setBtnSaveVisible(boolean btnSaveVisible) {
		this.btnSaveVisible = btnSaveVisible;
	}

	/**
	 * @return the listOfLoans
	 */
	public List<Loans> getListOfLoans() {
		return listOfLoans;
	}

	/**
	 * @param listOfLoans the listOfLoans to set
	 */
	public void setListOfLoans(List<Loans> listOfLoans) {
		this.listOfLoans = listOfLoans;
	}

	/**
	 * @return the loansSelected
	 */
	public Loans getLoansSelected() {
		return loansSelected;
	}

	/**
	 * @param loansSelected the loansSelected to set
	 */
	public void setLoansSelected(Loans loansSelected) {
		this.loansSelected = loansSelected;
	}

	/**
	 * @return the file
	 */
	public StreamedContent getFile() {
		return file;
	}

	/**
	 * @return the loansDataModel
	 */
	public LoansDataModel getLoansDataModel() {
		return loansDataModel;
	}

	/**
	 * @param mdbServices the mdbServices to set
	 */
	public void setMdbServices(MDBServices mdbServices) {
		this.mdbServices = mdbServices;
	}

	/**
	 * @return the listOfobjects
	 */
	public List<Object> getListOfobjects() {
		return listOfobjects;
	}

	/**
	 * @param listOfobjects the listOfobjects to set
	 */
	public void setListOfobjects(List<Object> listOfobjects) {
		this.listOfobjects = listOfobjects;
	}
	
	
}
